package com.hsd.service.impl;

import com.hsd.entity.Account;
import com.hsd.mapper.IAccountMapper;
import com.hsd.service.IAccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class IAccountServiceImpl implements IAccountService {
    @Resource
    IAccountMapper accountMapper;

    /**
     * 查所有账号
     *
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public List<Account> findAll() {
        return accountMapper.selectAll();
    }

    /**
     * 存钱
     *
     * @param acc   存钱账号
     * @param money 存多少钱
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public boolean save(String acc, Double money) {
        return accountMapper.updateMoney(acc, money) > 0;
    }

    /**
     * 取钱
     *
     * @param acc   取钱账号
     * @param money 取多少钱
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public boolean take(String acc, Double money) {
        Account account = findByAcc(acc);
        double balance = account.getMoney();//获取账户余额
        if (balance < money)
            throw new RuntimeException("余额不足");
        return accountMapper.updateMoney(acc, -money) > 0;
    }

    /**
     * 转账
     *
     * @param from  转出账号
     * @param to    转入账号
     * @param money 转多少钱
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public boolean transfer(String from, String to, Double money) {
        boolean take = take(from, money);
        boolean save = save(to, money);
        System.out.println("from:"+take+" to:"+save);
        if (!(take && save))
            throw new RuntimeException("转账异常");
        return take && save;
    }

    /**
     * 通过账号查询账户信息
     *
     * @param acc 查询账号
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public Account findByAcc(String acc) {
        return accountMapper.selectByAcc(acc);
    }

}
